'use strict'

const Controller = require('egg').Controller

class LeaveMessageController extends Controller {
    async getData () {
        const { ctx } = this
        const { page } = ctx.query
        const docs = await ctx.model.LeaveMessage.find().populate({
            path:'user_id',
            select:{ avatar:1,nickname:1 }
        }).skip((page - 1) * 8).limit(8).sort({ _id:-1 })
        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async create () {
        const { ctx } = this
        const { content } = ctx.query
        const docs = await ctx.model.LeaveMessage.create({ content,user_id:ctx.user._id })
        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async like () {
        const { ctx } = this
        const { type,_id } = ctx.query

        let docs

        if (type === 'up') {
            docs = await ctx.model.LeaveMessage.findOneAndUpdate({ _id },{
                $inc:{ like_count:1 },
                $push:{ like_id:ctx.user._id }
            },{ new:true })
        } else {
            docs = await ctx.model.LeaveMessage.findOneAndUpdate({ _id },{
                $inc:{ like_count:-1 },
                $pull:{ like_id:ctx.user._id }
            },{ new:true })
        }

        ctx.body = {
            state:'ok',
            data:docs
        }
    }
}

module.exports = LeaveMessageController
